package com.sj.parksdk.fragment.carmanage;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;
import com.ruffian.library.widget.helper.RBaseHelper;
import com.ruffian.library.widget.helper.RTextViewHelper;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.adapter.base.delegate.SimpleDelegateAdapter;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.fragment.certificate.FragmentCarCertificate;
import com.sj.parksdk.fragment.main.FragmentAddCar;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_Car;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.core.PageOption;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

@Page(name = "选择车辆",params = {Extras.BASE_TYPE,Extras.BASE_IS_SELECTED})
public class FragmentParkingPay extends BaseFragment {
    @BindView(R2.id.recycler_car)
    RecyclerView recyclerCar;
    @BindView(R2.id.ll_state)
    StatefulLayout llState;
    @BindView(R2.id.btn_add)
    SuperButton btnAdd;
    @AutoWired(name = Extras.BASE_TYPE)
    String type;
    @AutoWired(name = Extras.BASE_IS_SELECTED)
    String selectedType ;

    private SimpleDelegateAdapter<Data_Car> adapter;

    @Override
    protected void initArgs() {
        XRouter.getInstance().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_carmanage;
    }

    @Override
    protected void initViews() {
        initAdapter();
    }

    @Override
    protected void initData() {
        queryCar();
    }

    private void initAdapter() {
        adapter = new SimpleDelegateAdapter<Data_Car>(R.layout.parksdk_adapter_parking_pay_car, new LinearLayoutHelper()) {
            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, Data_Car item) {
                holder.text(R.id.tv_name, item.getCarNo());
                holder.visible(R.id.rtv_state_certification, item.isVerified() ? View.VISIBLE : View.GONE);
                holder.visible(R.id.rtv_state_pay, item.isAutoPay() ? View.VISIBLE : View.GONE);

                RTextView rtvCarColor = holder.findViewById(R.id.rtv_car_color);
                rtvCarColor.setText(Dictionary.Car.PlateColor.PlateColorNameMap.get(item.getPlateColor()));
                RTextViewHelper rtvCarColorHeler = rtvCarColor.getHelper();
                RLinearLayout rllCarColor = holder.findViewById(R.id.rll_car_color);
                RBaseHelper carBorderColoHelper = rllCarColor.getHelper();
                int carColor = ResUtils.getColor(Dictionary.Car.PlateColor.PalteColorMap.get(StringUtils.isEmpty(item.getPlateColor())?Dictionary.Car.PlateColor.Unknow:item.getPlateColor()));
                rtvCarColorHeler.setBackgroundColorNormal(carColor);
                rtvCarColorHeler.setTextColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(item.getPlateColor())?R.color.color_3:R.color.color_white));
                rtvCarColorHeler.setBorderWidthNormal(DensityUtils.dp2px(Dictionary.Car.PlateColor.White.equals(item.getPlateColor())?1:0));
                carBorderColoHelper.setBorderColorNormal(Dictionary.Car.PlateColor.White.equals(item.getPlateColor()) ?ResUtils.getColor(R.color.color_3):carColor);

                holder.click(R.id.ll_item, v -> gotoParkRecord(item));
            }
        };
        WidgetUtils.initRecyclerView(recyclerCar, DensityUtils.dp2px(10),ResUtils.getColor(R.color.color_cut_line));
        recyclerCar.setAdapter(adapter);
    }

    private void gotoParkRecord(Data_Car item) {
        if(Extras.BASE_SELECTED.equals(selectedType))setResultCar(item);
        else if(Extras.BASE_SELECTED_CERTICICATE.equals(selectedType))setResultCarForCertificate(item);
        else gotoRecord(item);
    }

    private void setResultCarForCertificate(Data_Car item) {
        if(item.isVerified()){
            showCannotDialog("车辆已经认证");
            return;
        }
        setResultCar(item);
    }

    private void showCannotDialog(String message) {
        new SweetAlertDialog(getContext(),SweetAlertDialog.ERROR_TYPE)
                .setContentText(message)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .showCancelButton(false)
                .setConfirmText(ResUtils.getString(R.string.OK))
                .setConfirmClickListener(null)
                .show();
    }

    private void gotoRecord(Data_Car item) {
        if(!item.isVerified()){
            showCetificatFirstDialog(item);
            return;
        }
        Bundle params = new Bundle();
        params.putLong(Extras.CAR_ID, item.getId());
        params.putString(Extras.CAR_NUMBER, item.getCarNo());
        params.putBoolean(Extras.CAR_IS_CETIFICAT, item.isVerified());
        params.putString(Extras.CAR_COLOR, item.getPlateColor());
        if(Extras.CAR_SELECTCAR_TYPE_PAY.equals(type))params.putBoolean(Extras.PARK_ORDER_UNFINISH,true);
        else if(Extras.CAR_SELECTCAR_TYPE_RECORD.equals(type)) params.putBoolean(Extras.PARK_ORDER_UNFINISH,false);
        openPage(FragmentParkRecord.class, params);
    }

    private void showCetificatFirstDialog(Data_Car item) {
        new SweetAlertDialog(getContext(), SweetAlertDialog.NORMAL_CENTER_TITLE_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(100))
                .setContentText(ResUtils.getString(R.string.dialog_certificat_first))
                .setConfirmText(ResUtils.getString(R.string.dialog_button_goto_cetificat))
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        gotoCarCetificat(item);
                        sweetAlertDialog.dismiss();
                    }
                }).setCancelClickListener(null).show();
    }
    //车辆认证
    private void gotoCarCetificat(Data_Car car) {
        PageOption.to(FragmentCarCertificate.class)
                .putLong(Extras.CAR_ID, car.getId())
                .putString(Extras.CAR_NUMBER, car.getCarNo())
                .putString(Extras.CAR_COLOR, car.getPlateColor())
                .putBoolean(Extras.CAR_IS_CETIFICAT, car.isVerified())
                .openForResult(this, Extras.REQUEST_CAR_CERTIFICATE);
    }

    private void setResultCar(Data_Car item) {
        Intent params = new Intent();
        params.putExtra(Extras.BASE_JSON, JsonUtil.toJson(item));
        setFragmentResult(RESULT_OK,params);
        popToBack();
    }

    @SingleClick
    @OnClick({R2.id.btn_add})
    public void onViewClicked(View view) {
        if(view.getId() != R.id.btn_add)return;
        PageOption.to(FragmentAddCar.class)
                .setRequestCode(Extras.REQUEST_CODE_ADD_CAR)
                .open(this);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK)return;
        if (data == null) return;
        if(requestCode == Extras.REQUEST_CODE_ADD_CAR)addCarResult(data);
        else if (requestCode == Extras.REQUEST_CAR_CERTIFICATE) refreshCarList(data);
    }
    private void refreshCarList(Intent data) {
        boolean success = data.getBooleanExtra(Extras.BASE_SUCCESS_TYPE, false);
        if (success) queryCar();
    }

    private void addCarResult(Intent data) {
        boolean addCarSuccess = data.getBooleanExtra(Extras.CAR_ADD_CAR, false);
        if (addCarSuccess) queryCar();
    }

    private void queryCar() {
        llState.showLoading();
        new MGetRequest(MyNetApi.CAR_CARS)
                .user()
                .params(MyNetApi.PageParam.pageIndex,1)
                .params(MyNetApi.PageParam.pageSize,100)
                .execute(new TipRequestCallBack<Data_Car>() {
                    @Override
                    public void onSuccess(Data_Car response) throws Throwable {
                        queryCarsSuccess(response);
                    }

                    @Override
                    public void onError(ApiException e) {
                        llState.showError(e.getMessage(),null);
                    }
                });
    }

    private void queryCarsSuccess(Data_Car data) {
        if(data == null || data.getItems() == null){
            llState.showCustom(emptyStatus());
            return;
        }
        if(data.getItems().size() == 0)llState.showCustom(emptyStatus());
        else llState.showContent();
        adapter.refresh(data.getItems());
    }
}
